package idu0080.veebitoorik.web;

import idu0080.veebitoorik.serviceclient.SOAPClient;
import idu0080.yl6_OpenERPServices_client.Invoice;

import java.io.IOException;
import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

/**
 * Servlet implementation class PaymentServlet
 */
@WebServlet("/payment")
public class PaymentServlet extends HttpServlet 
{
	private static final long serialVersionUID = 1L;
       
    /**
     * @see HttpServlet#HttpServlet()
     */
    public PaymentServlet() 
    {
        super();
    }

	/**
	 * @see HttpServlet#doGet(HttpServletRequest request, HttpServletResponse response)
	 */
	protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException 
	{
		doPost(request, response);
	}

	/**
	 * @see HttpServlet#doPost(HttpServletRequest request, HttpServletResponse response)
	 */
	protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException 
	{
		String s_invoice_number = null;
		Invoice selected_invoice = null;
		SOAPClient soapclient = new SOAPClient();
		String payment_number = "";
		Double payd_amount = Double.valueOf(0.0D);
		
		if ((request.getParameter("s_invoice_number") != null) && (!request.getParameter("s_invoice_number").equals("")))
		{
			s_invoice_number = request.getParameter("s_invoice_number");
			selected_invoice = soapclient.getInvoiceByNumber(s_invoice_number);
			request.setAttribute("selected_invoice", selected_invoice);
			request.setAttribute("s_invoice_number", s_invoice_number);
		}
		
		if ((request.getParameter("payd_amount") != null) && (!request.getParameter("payd_amount").equals("")))
		{
			payd_amount = Double.valueOf(Double.parseDouble(request.getParameter("payd_amount")));
		}
		
		if ((request.getParameter("what_to_do").equals("make_payment")) && (payd_amount.doubleValue() > 0.0D) && (selected_invoice != null))
		{
			payment_number = soapclient.makePayment(selected_invoice.getNumber(), selected_invoice.getPartnerId(), payd_amount);
			request.setAttribute("payment_number", payment_number);
			selected_invoice = soapclient.getInvoiceByNumber(s_invoice_number);
			request.setAttribute("selected_invoice", selected_invoice);
		}
		
		getServletConfig().getServletContext().getRequestDispatcher("/payment.jsp").forward(request, response);
	}

}
